<template>
  <div>
    <el-row class="p-d b-f header">
      <el-page-header @back="goBack" :content="title">
      </el-page-header>
      <span class="saveBtn" v-if="isFlag!=='look'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" plain @click="goBack">取消</el-button>
      </span>
    </el-row>
    <div class="p-d">
      <div class="p-d b-f">
        <el-row class="p-b">
          <h1 class="before">基本信息</h1>
        </el-row>
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="160px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="科研指南名称：" prop="name">
                <el-input v-model="form.name" placeholder="请输入科研指南名称" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指南预算：" prop="budget" class="flex-rowform">
                <el-input v-model="form.budget" placeholder="请输入指南预算" type="number" oninput="if(value<0)value=0" :disabled="isFlag=='look'" />
                <span class="r-span">（万元）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="年度：" prop="yearStr">
                <el-date-picker v-model="form.yearStr" style="width: 100%;" type="year" value-format="yyyy" placeholder="请选择年度"
                  :disabled="isFlag=='look'">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布单位：" prop="departmentName">
                <el-input v-model="form.departmentName" placeholder="请输入发布单位" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="上传文件：" prop="fileName">
                <el-upload v-if="isFlag!=='look'" ref="uploadRef" class="upload-demo" action="#" :limit="1" :on-change="handleChange"
                  :auto-upload="false" :show-file-list="false" :on-exceed="handleExceed" :accept="accept">
                  <template #trigger>
                    <el-button type="primary">选择文件</el-button>
                  </template>
                  <div slot="tip" class="el-upload__tip">
                    只支持上传.doc/.docx/.pdf文件
                  </div>
                  <div slot="tip" class="el-upload__tip" v-if="form.fileName">
                    <el-tag closable @close="closeFile">
                      {{form.fileName}}
                    </el-tag>
                  </div>
                </el-upload>
                <!-- <el-tooltip v-else
                  class="item"
                  effect="dark"
                  content="点击下载文件"
                  placement="top">
                  <el-link style="padding-top: 5px;"
                    type="primary"
                    :underline="false"
                    @click="downloadLink(form)">{{ form.fileName }}</el-link>
                </el-tooltip> -->
                <div v-else style="padding-top: 5px;">
                  <el-link type="primary" :underline="false">
                    {{ form.fileName?form.fileName:'暂无文件' }}
                  </el-link>
                  <el-button style="margin-left: 15px;" type="primary" size="mini" :underline="false" @click="lookLink(form)">
                    预览
                  </el-button>
                  <el-button style="margin-left: 15px;" type="primary" size="mini" :underline="false" @click="downloadLink(form)">
                    下载
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="p-d b-f m-t">
        <el-row class="p-b">
          <h1 class="before">指南条目</h1>
        </el-row>
        <div class="p-t">
          <SearchComp :searchForm="searchForm" :searchData="queryString" :searchAction="searchAction"></SearchComp>
        </div>
        <div>
          <div class="btnStyle" style="display: flex;" v-if="isFlag!=='look'">
            <el-upload ref="uploadRefXls" class="upload-demo" action="#" :limit="1" :on-change="handleChangeXls" :auto-upload="false"
              :show-file-list="false" :on-exceed="handleExceedXls" accept=".xls,.xlsx">
              <template #trigger>
                <el-button type="primary" size="small">批量导入</el-button>
              </template>
            </el-upload>
            <el-button class="m-l" type="primary" size="small" @click="download()">下载模板</el-button>
          </div>
          <TableCompEle class="m-t" ref="multipleTable" :tableData="tableData" :tableConfig="tableConfig" :tableAction="tableAction" :isSelect="false"
            :isIndex="true" :isShowPage="true" @getPagination="getDetail" :queryParams="queryParams"></TableCompEle>
        </div>
      </div>
    </div>
    <PreviewPdf v-if="showPdf" :pdfUrl="pdfUrl" @closeLookPdf="closeLookPdf" />
  </div>
</template>

<script>
import { uploadFile, deleteFile, getWord2Pdf } from '@/api/common.js'
import {
  addGuide,
  updateGuide,
  downloadTemplate,
  uploadAndExtractItem,
  getDetail
} from '@/api/guide.js'
import PreviewPdf from '@/views/common/previewPdf.vue'
export default {
  components: { PreviewPdf },
  computed: {
    isFlag() {
      return this.$route.params.flag
    },
    rowId() {
      return this.$route.params.id
    }
  },
  data() {
    return {
      showPdf: false,
      pdfUrl: null,
      title: '',
      accept: '.doc,.docx,.pdf',
      form: {
        name: '',
        budget: null,
        yearStr: '',
        departmentName: '',
        fileName: '',
        fileOriginPath: '',
        filePath: ''
      },
      rules: {
        name: [
          { required: true, message: '科研指南名称不能为空！', trigger: 'blur' }
        ],
        budget: [
          { required: true, message: '指南预算不能为空！', trigger: 'blur' }
        ],
        yearStr: [
          { required: true, message: '年度不能为空！', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '发布单位不能为空！', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '文件不能为空！', trigger: 'blur' }
        ]
      },
      queryParams: {
        total: 0,
        currentPage: 1,
        pageSize: 100000
      },
      allTableData: [],
      tableData: [],
      tableConfig: [
        {
          isEdit: true,
          isType: 'Input',
          prop: 'itemNo',
          placeholder: '请输入指南条目编号',
          label: '指南条目编号'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'itemName',
          placeholder: '请输入指南条目名称',
          label: '指南条目名称'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'domainName',
          placeholder: '请输入所属领域',
          label: '所属领域'
        }
      ],
      tableAction: {
        align: () => 'center',
        width: () => String(120),
        operations: [
          {
            label: '修改',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return !row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', true)
            }
          },
          {
            label: '删除',
            isLink: true,
            type: 'danger',
            isShow: row => {
              return !row.isHandle
            },
            method: row => {
              this.deleteFun(row)
            }
          },
          {
            label: '保存',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', false)
            }
          },
          {
            label: '取消',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', false)
            }
          }
        ]
      },
      queryString: {
        itemName: '',
        domainName: ''
      },
      searchForm: {
        formData: [
          {
            type: 'Input',
            label: '指南条目名称',
            prop: 'itemName',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入指南条目名称'
          },
          {
            type: 'Input',
            label: '所属领域',
            prop: 'domainName',
            clearable: true,
            icon: 'el-icon-search',
            placeholder: '请输入所属领域'
          }
        ]
      },
      searchAction: [
        {
          label: '查询',
          type: 'primary',
          handle: () => { }
        },
        {
          label: '重置',
          type: 'primary',
          plain: true,
          handle: () => {
            this.queryString = {
              itemName: '',
              domainName: ''
            }
          }
        }
      ]
    }
  },
  created() {
    switch (this.isFlag) {
      case 'add':
        this.title = '新增指南'
        break
      case 'edit':
        this.title = '修改指南'
        this.getDetail()
        break
      case 'look':
        this.title = '查看指南指南'
        this.getDetail()
        break
    }
  },
  watch: {
    'queryString.itemName'(newValue) {
      this.tableData = this.allTableData.filter(
        item => item.itemName.indexOf(newValue) > -1
      )
    },
    'queryString.domainName'(newValue) {
      this.tableData = this.allTableData.filter(
        item => item.domainName.indexOf(newValue) > -1
      )
    },
    deep: true
  },
  mounted() { },
  methods: {
    downloadLink(item) {
      this.downloadByUrl(item.fileName, item.filePath)
    },
    lookLink(item) {
      let txt = this.getMatchType(item.filePath)
      if (txt === 'word') {
        getWord2Pdf({ wordPath: item.filePath }).then(res => {
          if (res.data) {
            this.lookPdf(res.data)
          } else {
            this.$message.warning('暂无法预览，请下载后查看！')
          }
        })
      } else {
        if (txt === 'pdf') {
          this.lookPdf(item.filePath)
        } else {
          this.$message.warning('文件不支持预览！')
        }
      }
    },
    lookPdf(url) {
      this.pdfUrl = url
      this.showPdf = true
    },
    closeLookPdf() {
      this.showPdf = false
      this.pdfUrl = null
    },
    getDetail() {
      getDetail({ id: this.rowId }).then(res => {
        this.form = res.data.techGuide
        this.allTableData = res.data.techGuideItems
        this.tableData = res.data.techGuideItems
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    submitForm() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let params = {
            techGuide: this.form,
            techGuideItems: this.tableData
          }
          if (this.isFlag == 'add') {
            addGuide(params).then(() => {
              this.goBack()
            })
          } else {
            updateGuide(params).then(() => {
              this.goBack()
            })
          }
        } else {
          return false
        }
      })
    },
    handleChange(file) {
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadFile(formData).then(res => {
        this.form.fileName = res.data.fileName
        this.form.fileOriginPath = res.data.filePath
        this.form.filePath = res.data.servicePath
      })
    },
    // 多次上传覆盖
    handleExceed(file) {
      this.$refs.uploadRef.clearFiles()
      this.handleChange(file[0])
    },
    // 下载模板
    download() {
      downloadTemplate()
    },
    // xls
    handleChangeXls(file) {
      // uploadAndExtractItem
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadAndExtractItem(formData).then(res => {
        this.allTableData = res.data
        this.tableData = res.data
      })
    },
    // 多次上传覆盖
    handleExceedXls(file) {
      this.$refs.uploadRefXls.clearFiles()
      this.handleChangeXls(file[0])
    },
    deleteFun(row) {
      let itemIndex = this.tableData.findIndex(function (obj) {
        return row === obj
      })
      // this.tableData.splice(itemIndex, 1)
      this.allTableData.splice(itemIndex, 1)
    },
    closeFile() {
      deleteFile({ files: [this.form.fileOriginPath] }).then(() => {
        this.form.fileName = ''
        this.form.fileOriginPath = ''
        this.form.filePath = ''
      })
    }
  }
}
</script>

<style lang="less" scoped>
  ::v-deep.flex-rowform {
    .el-form-item__content {
      display: flex;
    }
    .r-span {
      display: inline-block;
      width: 100px;
      line-height: 40px;
    }
  }
  .header {
    position: relative;
    .saveBtn {
      position: absolute;
      right: 20px;
      top: 10px;
    }
  }
</style>